package com.xzmzhp.controller.people;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.PolicyConditions;
import com.xzmzhp.config.AliOssConfig;
import com.xzmzhp.constant.ReturnConstant;
import com.xzmzhp.security.LoginService;
import com.xzmzhp.security.LoginUser;
import com.xzmzhp.utils.StringUtils;
import com.xzmzhp.utils.return_tool.AliOssPolicy;
import com.xzmzhp.utils.return_tool.ReturnData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 王源(xm)
 * @create: 2021-06-01 10:40
 * @program: ams
 * @description: 公共交互类
 */

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/common")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private AliOssConfig aliOssConfig;

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return token
     */
    @PostMapping("/login")
    public ReturnData login(String username, String password) {
        return loginService.login(username, password);
    }

    /**
     * 获取用户信息
     * @param authentication 安全认证
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public ReturnData getInfo(Authentication authentication){
        LoginUser loginUser =  (LoginUser) authentication.getPrincipal();
        if (StringUtils.isNotNull(loginUser)){
            String[] roles = {loginUser.getUser().getCompetenceName()};
            Map<String,Object> map = new HashMap<>();
            map.put("personnelName",loginUser.getUser().getPersonnelName());
            map.put("roles",roles);
            map.put("studentId",loginUser.getUser().getStudentId());
            return ReturnData.ok(map);
        }
        return ReturnData.error(ReturnConstant.FAIL,"查询用户信息失败");
    }


    /**
     * 前端获取直传的policy信息
     * 前端可以使用响应的参数进行直传到oss存储
     *
     * @return policy信息
     */
    @GetMapping("/policy")
    public AliOssPolicy getPolicy() {
        // 创建OSS客户端
        OSS client = new OSSClientBuilder().build(aliOssConfig.getEndpoint(), aliOssConfig.getAccessId(), aliOssConfig.getAccessKey());
        // 直传有效截止时间
        long expireEndTime = System.currentTimeMillis() + (aliOssConfig.getExpireTime() * 1000);
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConditions = new PolicyConditions();
        // 设置可上传文件的大小
        policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, aliOssConfig.getMin(), aliOssConfig.getMin());
        // 生成policy
        String postPolicy = client.generatePostPolicy(expiration, policyConditions);
        byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = client.calculatePostSignature(postPolicy);
        // 封装policy等信息
        AliOssPolicy aliOssPolicy = new AliOssPolicy();
        aliOssPolicy.setOssAccessKeyId(aliOssConfig.getAccessId());
        aliOssPolicy.setPolicy(encodedPolicy);
        aliOssPolicy.setSignature(postSignature);
        aliOssPolicy.setHost(aliOssConfig.getHost());
        aliOssPolicy.setExpire(String.valueOf(expireEndTime / 1000));
        return aliOssPolicy;
    }

}
